package com.msg.xml;

import java.util.List;

/**
 * A manipulator object which compute the difference of sold seats information in {@code price_code}
 * table and current data from uploaded xml file, and update this difference in {@code Remaining_prediction} table
 * @author jeson9603
 *
 */
public class RemainPrediction_Manipulator extends Table_Manipulator {

	private String ticketLvId = null;
	private String seats = null;
	
	public RemainPrediction_Manipulator(Property prop) {
		super(prop);
	}
	
	@Override
	protected String getSpecificData() {
		return null;
	}

	@Override
	protected String update() {
		String groupId = prop.getTicketGroupId();
		String predictionId = prop.getPredictionId();
		
		
		if(!TableUtility.checkSalePrediction(predictionId, prop.getEVENT_ID()))
			predictionId = "7";
		
		
		DBRequest groupRequest = TableUtility.bindGroupKeys(ticketLvId, groupId, "Event_Id", prop.getEVENT_ID());
		groupRequest.resultCol.remove("Event_Id");
		groupRequest.resultCol.add("Sold_Seats");
		
		List<String> seatsInformation = DBhandler.getData("price_code", groupRequest);
		
		DBRequest predictionRequest = TableUtility.bindPredictionKeys(ticketLvId, predictionId, "Event_Id", prop.getEVENT_ID());
		
		
		String seatsDiff = null;
		//there's no seats data in price_code table, set the seats difference to be the new seats data
		if(seatsInformation.size() == 0) {
			seatsDiff = seats;
		}
		//there's seats data exist, compute the difference of new seats data and old one in price_code
		else {
			String groupSeats = seatsInformation.get(0);
			if(groupSeats.compareTo("null") == 0)
				groupSeats = "0";
			seatsDiff = String.valueOf(Integer.parseInt(seats) - Integer.parseInt(groupSeats));
		}	
		
		if(DBhandler.hasData("Remaining_Sale_Prediction", predictionRequest)) {
			predictionRequest.resultCol.remove("Event_Id");
			predictionRequest.resultCol.add("Number_Of_Seats");
			String predictedSeats = DBhandler.getData("Remaining_Sale_Prediction", predictionRequest).get(0);
			if(predictedSeats.compareTo("null") == 0)
				predictedSeats = "0";
			seatsDiff = String.valueOf(Integer.parseInt(predictedSeats) - Integer.parseInt(seatsDiff));
			predictionRequest.resultColData.add(seatsDiff);
			DBhandler.updateData("Remaining_Sale_Prediction", predictionRequest);
		}
		else {
			predictionRequest.entries.add("Number_Of_Seats");
			predictionRequest.data.add(seatsDiff);
			DBhandler.insertData("Remaining_Sale_Prediction", predictionRequest);
		}
		return null;
	}

	/**
	 * get the ticket level id and former sold seats information
	 * @param o string for ticket level id
	 */
	@Override
	protected void pushData(Object o) {
		if(o instanceof String) {
			String content = (String)o;
			if(content.startsWith("id_")) {
				ticketLvId = content.substring(3);
			}
			else {
				seats = content.substring(6);
			}
		}
	}

}
